package com.alkaid.anime.config;

import com.alkaid.anime.filter.JwtAuthorizationFilter;
import com.alkaid.commons.msg.MsgDefinition;
import com.alkaid.commons.utils.JsonResult;
import com.alkaid.commons.utils.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author Kylin
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        // 添加自定义拦截器
        http.addFilter(new JwtAuthorizationFilter(authenticationManager()));
        http.authorizeRequests()
                .antMatchers("/api/anime/hot_list/?*", "/api/anime/all/?*").permitAll()
                .antMatchers("/api/anime/count_list/?*", "/api/anime/play/**").permitAll()
                .antMatchers("/api/anime/get_refresh", "/api/anime/indicator").permitAll()
                .antMatchers("/api/anime/recent/?*", "/api/anime/comment/?*").permitAll()
                .anyRequest().authenticated()
                .and().formLogin();
        http.exceptionHandling()
                .authenticationEntryPoint((req, resp, e) -> {
                    // 请先登录
                    JwtUtils.responseStatus(resp, new JsonResult<>(201, null, MsgDefinition.LOGIN_PLEASE));
                })
                .accessDeniedHandler((req, resp, e) -> {
                    // 权限不足
                    JwtUtils.responseStatus(resp, new JsonResult<>(403, null, MsgDefinition.AUTHORITY_LOSS));
                });
    }
}
